package com.atguigu.gulimall.product.exception;

import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;

@Slf4j//日志
//@ControllerAdvice(basePackages = "com.atguigu.gulimall.product.app")//处理那个包路径的异常
@RestControllerAdvice(basePackages = "com.atguigu.gulimall.product.app")
public class GulimallExceptionControllerAdvice {

    /**
     * 处理表单参数也就是entity定义的异常MethodArgumentNotValidException
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class) // 这个方法能够处理什么异常
    public R handleValidException(MethodArgumentNotValidException e){
        log.error("数据校验出现问题{},异常类型{}",e.getMessage(),e.getClass());
        BindingResult bindingResult = e.getBindingResult();//获取到所有的校验异常
        HashMap<String, String> map = new HashMap<>();
        if(bindingResult.hasErrors()){
            bindingResult.getFieldErrors().forEach((item)->{
                map.put(item.getField(),item.getDefaultMessage());
            });
        }

        return R.error(BizCodeEnume.VALID_EXCEPTION.getCode(), BizCodeEnume.VALID_EXCEPTION.getMsg()).put("data",map);
    }

    /**
     * 处理其他的异常
     *
     * @param t
     * @return
     */
    @ExceptionHandler(value = Throwable.class)
    public R handlerException(Throwable t){
        log.info("系统异常{}",t);
        return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(),BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
    }

}
